package com.delu.filter;

import com.alibaba.fastjson.JSONObject;
import com.delu.data.Result;
import com.delu.em.ResultEnum;
import com.delu.utils.JwtUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import com.delu.dto.UserDTO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Component
public class LoginFilter extends ZuulFilter {
    /**
     * 配置过滤类型，有四种不同生命周期的过滤器类型
     * 1. pre：路由之前
     * 2. routing：路由之时
     * 3. post：路由之后
     * 4. error：发送错误调用
     * @return
     */
    @Autowired
    private JwtUtil jwtUtil;
    private RedisTemplate redisTemplate;
    private static List<String> ignoreURL = new ArrayList<>();
    static {
        ignoreURL.add("/user");
    }

    @Override
    public String filterType() {
        return "pre";
    }
   //由于网关可以写多个过滤器,根据这个方法返回数字大小来决定谁先执行,数字越小执行越早
    @Override
    public int filterOrder() {
        return 0;
    }
    //表示是否开启过滤器
    @Override
    public boolean shouldFilter() {
        RequestContext currContext = RequestContext.getCurrentContext();

        HttpServletRequest request = currContext.getRequest();
        String requestURL = request.getRequestURI();
//        if (ignoreURL.contains(requestURL)){
//            return  false;
//        }
        return false;//true表示拦截,false表示不拦截放过
    }
    @Override
    public Object run() throws ZuulException {
        //获取当前线程请求上下文类
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取request域对象
        HttpServletRequest request = currentContext.getRequest();
        //获取参数
        String authToken = request.getHeader("authToken");
        //校验用户名是否存在，如果不存在，说明用户未登录，不放过
        if (authToken == null || "".equals(authToken)) {
            //设置响应域对象
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(400);
            //获取response
            HttpServletResponse response = currentContext.getResponse();
            try {
                response.setContentType("text/html;charset=utf-8");
                Result result = Result.response(ResultEnum.NOLOGIN);
                response.getWriter().write(JSONObject.toJSONString(result));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            Claims claims = jwtUtil.parseJwt(authToken);
            claims.getId();
            claims.getSubject();
        } catch (Exception e1) {
            if (authToken == null || "".equals(authToken) || (UserDTO) redisTemplate.boundValueOps(authToken).get() == null) {
                //设置响应域对象
                currentContext.setSendZuulResponse(false);
                currentContext.setResponseStatusCode(400);
                //获取response
                HttpServletResponse response = currentContext.getResponse();
                try {
                    response.setContentType("text/html;charset=utf-8");
                    Result result = Result.response(ResultEnum.NOLOGIN);
                    response.getWriter().write(JSONObject.toJSONString(result));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return null;
    }
}
